<?php
/**
 *  redis 相关
 */

namespace app\common\service;

use think\Log;

class Redis
{
    private static $_redis;

    /**
     * @param int $database
     * @return \Redis
     */
    private static function init($database = 0)
    {
        self::connect($database);

        try {
            if (self::$_redis[$database]->ping() == '+PONG') {
                return self::$_redis[$database];
            }
            self::$_redis[$database]->close();  //phpRedis 4.2.0
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            try {
                self::$_redis[$database]->close();  //phpRedis 4.2.0
            } catch (\Exception $exception) {
                Log::error($exception->getMessage());
            }
        }
        self::connect($database);
        return self::$_redis[$database];
    }

    private static function connect($database) {
        if (empty(self::$_redis[$database])) {
            $config = config('redis');
            self::$_redis[$database] = new \Redis();
            if ($config['persistent']) {
                
                self::$_redis[$database]->pconnect($config['host'], $config['port'], 0, 'persistent_id_' . $database);
            } else {
                self::$_redis[$database]->connect($config['host'], $config['port']);
            }
            self::$_redis[$database]->auth($config['password']);
            self::$_redis[$database]->select($database);
        }
    }


    /** 默认 redis 实例
     * @return \Redis
     */
    public static function getInstance()
    {
        return self::init(0);
    }
}